import Flutter
import UIKit
import ZHNScan

public class DemoScanPlugin: NSObject, FlutterPlugin {
    
    private var result: FlutterResult?
    private let scanVC = ScanVC()
    private var hostViewController: UIViewController?

    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "demo_scan", binaryMessenger: registrar.messenger())
        let instance = DemoScanPlugin()
        if let window = UIApplication.shared.delegate?.window, let rootViewController = window?.rootViewController {
            instance.hostViewController = rootViewController
        } else {
            instance.hostViewController = UIViewController()
        }
        instance.hostViewController = UIApplication.shared.delegate?.window!?.rootViewController
        registrar.addMethodCallDelegate(instance, channel: channel)
    }

    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "scan" { // 扫码
            self.result = result
            self.showScanView()
        } else if call.method == "getPlatformVersion"  { // 默认的实现
            result("iOS " + UIDevice.current.systemVersion)
        } else if call.method == "dismiss" { // 返回方法
            leftNavButtonAction()
        } else { // 找不到方法
            result(FlutterMethodNotImplemented)
        }
    }
    
    func showScanView() {
        let kNavBarColor = #colorLiteral(red: 0.1843137255, green: 0.1882352941, blue: 0.1960784314, alpha: 1)
        let navigationController = UINavigationController(rootViewController: scanVC)
        navigationController.navigationBar.isTranslucent = true
        navigationController.navigationBar.barStyle = .black
        navigationController.navigationBar.barTintColor = kNavBarColor
        navigationController.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]

        scanVC.title = "扫描二维码"

        scanVC.scanClosure = { [weak self] codeString in
            guard let `self` = self else { return }
            guard let result = self.result else {
                return
            }
            result(codeString)
        }
        createNavButton(imageName: "backIcon", action: #selector(leftNavButtonAction), vc: scanVC)
        navigationController.modalPresentationStyle = .fullScreen
        self.hostViewController?.present(navigationController, animated: false, completion: nil)
    }

    /// 创建导航栏图片按钮
    private func createNavButton(imageName name: String, isLeft: Bool = true, action: Selector, vc: UIViewController) {
        var image = UIImage(named: name, in: getBundle(), compatibleWith: nil)
        // 让navigationItem的UIBarButtonItem的背景色不为蓝色
        image = image?.withRenderingMode(.alwaysOriginal)
        let item = UIBarButtonItem(image: image, style: .plain, target: self, action: action)
        if isLeft {
            vc.navigationItem.leftBarButtonItem = item
        } else {
            vc.navigationItem.rightBarButtonItem = item
        }
    }
    
    @objc private func leftNavButtonAction() {
        self.hostViewController?.dismiss(animated: true, completion: nil)
    }
    
    private func getBundle() -> Bundle {
        var bundle = Bundle(for: DemoScanPlugin.self)
        if let resourcePath = bundle.path(forResource: "demo_scan", ofType: "bundle") {
            if let resourcesBundle = Bundle(path: resourcePath) {
                bundle = resourcesBundle
            }
        }
        return bundle
    }
}
